package org.example.mylogin.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import freemarker.template.utility.StringUtil;
import jakarta.annotation.Resource;
import org.example.mylogin.dto.MemberLoginDTO;
import org.example.mylogin.entity.Member;
import org.example.mylogin.mapper.MemberMapper;
import org.example.mylogin.service.MemberService;
import org.example.mylogin.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2024-04-12
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String login(MemberLoginDTO memberLoginDTO) {

        //查看有没有这个用户
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        //课上这块是null与“”的区别注意and与or的写法
        queryWrapper.eq(StrUtil.isNotBlank(memberLoginDTO.getPhone()),Member::getPhone, memberLoginDTO.getPhone());
        queryWrapper.eq(StrUtil.isNotBlank(memberLoginDTO.getEmail()),Member::getEmail, memberLoginDTO.getEmail());

        Member member=this.getOne(queryWrapper);

        if(member == null)
        {
            //为什么要新建一个，不然会 报空指针
            member = new Member();

            member.setPhone(memberLoginDTO.getPhone());
            member.setEmail(memberLoginDTO.getEmail());

            //密码加密
            member.setPassword(BCrypt.hashpw(memberLoginDTO.getPassword()));

            this.save(member);
        }

        String id = member.getMemberId();

        //获取token
        String token = jwtUtil.createJwt(id);

        redisTemplate.opsForValue().set("Member_token_"+id, token, 60*60, TimeUnit.SECONDS);

        return token;
    }
}
